<template>
  <el-dialog
    title="编辑用户"
    v-model="dialogVisible"
    width="50%"
    :before-close="handleClose"
  >
    <el-tabs v-model="activeTab" @tab-click="handleTabChange">
      <el-tab-pane label="基本信息" name="basic">
        <el-form :model="roleForm" label-width="120px">
          <el-form-item label="角色名称">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="roleForm.description" type="textarea" />
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="权限管理" name="permissions">
        <div v-loading="permissionsLoading">
          <div class="permission-header">
            <div class="permission-select">
              <el-select
                v-model="selectedPermission"
                placeholder="选择要添加的权限"
                style="width: 300px"
              >
                <el-option
                  v-for="perm in availablePermissions"
                  :key="perm.code"
                  :label="perm.description"
                  :value="perm.code"
                >
                  <span>{{ perm.description }}</span>
                  <span
                    class="permission-risk-level"
                    :class="getRiskLevelType(perm.riskLevel)"
                  >
                    {{ getRiskLevelName(perm.riskLevel) }}
                  </span>
                </el-option>
              </el-select>
              <el-button
                type="primary"
                @click="addPermission"
                :disabled="!selectedPermission"
              >
                添加权限
              </el-button>
            </div>
          </div>

          <el-table
            :data="userPermissions"
            style="width: 100%"
            v-if="userPermissions.length > 0"
          >
            <el-table-column prop="code" label="权限代码" width="180" />
            <el-table-column prop="description" label="描述" />
            <el-table-column prop="riskLevel" label="风险等级" width="100">
              <template #default="scope">
                <el-tag :type="getRiskLevelType(scope.row.riskLevel)">
                  {{ getRiskLevelName(scope.row.riskLevel) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="scope">
                <el-button
                  type="danger"
                  size="small"
                  @click="removePermission(scope.row)"
                >
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-empty description="暂无权限" v-else />
        </div>
      </el-tab-pane>
    </el-tabs>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          @click="saveRole"
          v-if="activeTab === 'basic'"
        >
          保存
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import { usePermissionService } from "@/stores/permissionService";
import { ElMessage, ElMessageBox } from "element-plus";

const permissionService = usePermissionService();
const dialogVisible = ref(false);
const activeTab = ref("basic");

// 基本表单数据
const roleForm = reactive({
  id: null,
  name: "",
  description: "",
});

// 权限管理相关数据
const userPermissions = ref([]);
const availablePermissions = ref([]);
const selectedPermission = ref("");
const permissionsLoading = ref(false);
const currentUserId = ref(null);

// 获取用户权限列表
const fetchUserPermissions = async () => {
  if (!currentUserId.value) return;

  permissionsLoading.value = true;
  try {
    const permissions = await permissionService.getUsePermission(
      currentUserId.value,
    );
    userPermissions.value = permissions;
    generateAvailablePermissions();
  } catch (error) {
    console.error("获取用户权限失败:", error);
    ElMessage.error("获取用户权限失败");
  } finally {
    permissionsLoading.value = false;
  }
};

// 生成可用权限列表（示例权限，实际应从后端获取）
const generateAvailablePermissions = () => {
  // 这里是示例权限，实际应该从后端获取完整的权限列表
  const allPermissions = [
    { code: "user:view", description: "查看用户", riskLevel: 1 },
    { code: "user:create", description: "创建用户", riskLevel: 2 },
    { code: "user:edit", description: "编辑用户", riskLevel: 2 },
    { code: "user:delete", description: "删除用户", riskLevel: 3 },
    { code: "role:view", description: "查看角色", riskLevel: 1 },
    { code: "role:create", description: "创建角色", riskLevel: 2 },
    { code: "role:edit", description: "编辑角色", riskLevel: 2 },
    { code: "role:delete", description: "删除角色", riskLevel: 3 },
    { code: "course:view", description: "查看课程", riskLevel: 1 },
    { code: "course:create", description: "创建课程", riskLevel: 2 },
    { code: "course:edit", description: "编辑课程", riskLevel: 2 },
    { code: "course:delete", description: "删除课程", riskLevel: 3 },
    { code: "assessment:view", description: "查看评估", riskLevel: 1 },
    { code: "assessment:create", description: "创建评估", riskLevel: 2 },
    { code: "assessment:edit", description: "编辑评估", riskLevel: 2 },
    { code: "assessment:delete", description: "删除评估", riskLevel: 3 },
  ];

  // 过滤掉用户已有的权限
  const userPermCodes = userPermissions.value.map((p) => p.code);
  availablePermissions.value = allPermissions.filter(
    (p) => !userPermCodes.includes(p.code),
  );
};

// 添加权限
const addPermission = async () => {
  if (!selectedPermission.value || !currentUserId.value) return;

  permissionsLoading.value = true;
  try {
    // 使用更新后的 addUserPermission 方法，传递用户ID和权限代码
    await permissionService.addUserPermission(
      currentUserId.value,
      selectedPermission.value,
    );
    ElMessage.success("权限添加成功");
    await fetchUserPermissions(); // 重新获取权限列表
    selectedPermission.value = ""; // 清空选择
  } catch (error) {
    console.error("添加权限失败:", error);
    ElMessage.error("添加权限失败");
  } finally {
    permissionsLoading.value = false;
  }
};

// 移除权限
const removePermission = (permission) => {
  ElMessageBox.confirm(
    `确定要移除权限 "${permission.description}" 吗？`,
    "警告",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    },
  )
    .then(async () => {
      permissionsLoading.value = true;
      try {
        // 使用更新后的 deleteUserPermission 方法，传递用户ID和权限代码
        await permissionService.deleteUserPermission(
          currentUserId.value,
          permission.code,
        );
        ElMessage.success("权限移除成功");
        await fetchUserPermissions(); // 重新获取权限列表
      } catch (error) {
        console.error("移除权限失败:", error);
        ElMessage.error("移除权限失败");
      } finally {
        permissionsLoading.value = false;
      }
    })
    .catch(() => {
      // 取消操作
    });
};

// 获取风险等级类型
const getRiskLevelType = (level) => {
  const types = {
    1: "info",
    2: "warning",
    3: "danger",
  };
  return types[level] || "info";
};

// 获取风险等级名称
const getRiskLevelName = (level) => {
  const names = {
    1: "低风险",
    2: "中风险",
    3: "高风险",
  };
  return names[level] || "未知";
};

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false;
};

// 保存角色
const saveRole = () => {
  console.log("保存角色:", roleForm);
  // 这里添加保存角色的逻辑
  ElMessage.success("保存成功");
  dialogVisible.value = false;
};

// 监听标签页切换
const handleTabChange = (tab) => {
  fetchUserPermissions();
};

// 监听标签页变化
watch(activeTab, (newVal) => {
  if (newVal === "permissions") {
    fetchUserPermissions();
  }
});

// 打开弹窗并初始化数据
const open = (user, tabName = "basic") => {
  // 设置当前用户ID
  currentUserId.value = user.id;

  // 设置基本表单数据
  roleForm.name = user.username || "";
  roleForm.description = user.description || "";

  // 设置活动标签页
  activeTab.value = tabName;

  // 如果是权限标签页，立即获取用户权限
  if (tabName === "permissions") {
    fetchUserPermissions();
  }

  // 显示弹窗
  dialogVisible.value = true;
};

// 暴露方法给父组件
defineExpose({
  open,
});
</script>

<style scoped>
.permission-header {
  margin-bottom: 20px;
}

.permission-select {
  display: flex;
  gap: 10px;
  align-items: center;
}

.permission-risk-level {
  margin-left: 10px;
  font-size: 12px;
}

.permission-risk-level.info {
  color: #909399;
}

.permission-risk-level.warning {
  color: #e6a23c;
}

.permission-risk-level.danger {
  color: #f56c6c;
}
</style>
